package rest

import (
	"net/http"
	"encoding/json"
	"fmt"
	"io/ioutil"
)

func WriteObject(w http.ResponseWriter, req *http.Request, obj interface{}) error {

	text, err := json.Marshal(obj)

	if err != nil {
		return err
	}

	cb := req.FormValue("callback")

	if cb != "" {
		fmt.Fprintf(w, "%s(%s);", cb, string(text))
	} else {
		w.Write(text)
	}

	return nil
}

func ReadObject(req *http.Request, obj interface{}) error {

	body, err := ioutil.ReadAll(req.Body)

	if err != nil {
		return err
	}

	err = json.Unmarshal(body, obj)

	if err != nil {
		return err
	}

	return nil
}
